package com.quectel.cms.controller.invoice;


import cn.hutool.core.date.DateTime;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.core.invoice.InvoiceConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.invoice.dto.InvoiceDto;
import com.quectel.core.module.invoice.dto.InvoiceItemDto;
import com.quectel.core.module.invoice.service.InvoiceService;
import com.quectel.util.common.*;
import com.quectel.util.kit.PageFetchKit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/03/31 16:28
 */
@RestController
@RequestMapping("invoice")
@Tag(name = "InvoiceController", description = "开票记录表相关api")
public class InvoiceController extends BaseController {

    @DubboReference
    private InvoiceService invoiceService;


    /**
     * 导出开票申请记录
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "invoice:exportExcel")
    public void exportExcel(HttpServletRequest httpServletRequest, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        if (request.isNotBlank(SystemConstants.STATUS_FLAG)) {
            String[] statusArrays = request.getString(SystemConstants.STATUS_FLAG).split(",");
            request.put(SystemConstants.STATUSES, statusArrays);
        }

        List<InvoiceDto> result = PageFetchKit.fetchAll(reqParams -> invoiceService.queryList(reqParams), request.getParams(), 500);

        String[] headers = new String[]{"订单ID", "费用类型", "抬头类型", "发票抬头", "开票金额", "发票号", "发票属性", "开票状态", "申请人", "创建时间", "开票人", "开票时间"};
        List<String[]> dataList = new ArrayList<>();
        for (InvoiceDto data : result) {

            List<Long> bookNoList = new ArrayList<>();
            if (data.getInvoiceItems() != null && CollectionUtils.isNotEmpty(data.getInvoiceItems())) {
                bookNoList = data.getInvoiceItems().stream().map(InvoiceItemDto::getSourceId).collect(Collectors.toList());
            }
            String[] item = new String[headers.length];
            item[0] = JacksonUtils.toJsonString(bookNoList);

            InvoiceConstants.InvoiceItemSourceType sourceType = InvoiceConstants.InvoiceItemSourceType.find(data.getSourceType());
            item[1] = sourceType == null ? "" : sourceType.getDesc();
            item[2] = SysCodeUtils.easyToGetName(InvoiceConstants.INVOICE_TITLE_TYPE, String.valueOf(data.getInvoiceTitleType()));
            item[3] = data.getInvoiceTitleName();
            item[4] = data.getInvoiceAmount() == null ? "" : data.getInvoiceAmount().toString();
            item[5] = data.getInvoiceNo();
            item[6] = SysCodeUtils.easyToGetName(InvoiceConstants.INVOICE_NATURE, String.valueOf(data.getInvoiceNature()));
            item[7] = SysCodeUtils.easyToGetName(InvoiceConstants.INVOICE_STATUS, String.valueOf(data.getStatus()));
            item[8] = data.getPersonName();
            item[9] = data.getCreateTime() != null ? DateUtils.format(data.getCreateTime(), DateUtils.FormatType.SIMPLE) : null;
            item[10] = data.getInvoicePerson();
            item[11] = data.getInvoiceTime() != null ? DateUtils.format(data.getInvoiceTime(), DateUtils.FormatType.COMMON) : null;
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "开票申请记录", headers, dataList, "开票申请记录");

    }

    /**
     * 修改
     *
     * @param invoiceDto
     * @return
     */
    @PostMapping("invoice")
    @RequirePermissions(values = {"invoice:invoice"})
    @Operation(summary = "修改单条记录")
    public Response<Object> invoice(@RequestBody @Validated InvoiceDto invoiceDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(invoiceDto.getId()));
        if (invoiceService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        invoiceDto.setStatus(InvoiceConstants.InvoiceStatus.WAS_INVOICE.getType());
        invoiceDto.setInvoicePerson(SessionHolder.getSysUser().getUsername());
        invoiceDto.setInvoiceTime(DateTime.now());
        ;

        //填充基础数据
        fillEditCommonData(invoiceDto);

        invoiceService.saveOrUpdate(invoiceDto);

        return Response.ok();
    }

    private void replaceNode(JsonNode requestNode, ObjectNode sourceNode, String fieldName) {
        if (requestNode.get(fieldName) != null) {
            sourceNode.replace(fieldName, requestNode.get(fieldName));
        }
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "invoice:list")
    @Operation(summary = "分页列表")
    public Response<Page<InvoiceDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = invoiceService.queryTotal(request.getParams());

        List<InvoiceDto> list = null;
        if (total > 0) {
            list = invoiceService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<InvoiceDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<InvoiceDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = {"invoice:invoice", "invoice:edit"})
    @Operation(summary = "查询单条记录")
    public Response<InvoiceDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (invoiceService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        InvoiceDto invoiceDto = invoiceService.selectById(id);

        return Response.<InvoiceDto>ok().wrap(invoiceDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "invoice:info")
    @Operation(summary = "查询单条记录")
    public Response<InvoiceDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (invoiceService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        InvoiceDto invoiceDto = invoiceService.selectById(id);

        return Response.<InvoiceDto>ok().wrap(invoiceDto);
    }

    /**
     * 保存
     *
     * @param invoiceDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "invoice:edit")
    @Operation(summary = "保存单条记录")
    public Response<Object> save(@RequestBody @Validated InvoiceDto invoiceDto) {

        //填充基础数据
        fillSaveCommonData(invoiceDto);

        invoiceService.save(invoiceDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param invoiceDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "invoice:edit")
    @Operation(summary = "修改单条记录")
    public Response<Object> update(@RequestBody @Validated InvoiceDto invoiceDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(invoiceDto.getId()));
        if (invoiceService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(invoiceDto);

        invoiceService.updateById(invoiceDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "invoice:delete")
    @Operation(summary = "批量删除记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (invoiceService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        invoiceService.deleteBatch(ids);

        return Response.ok();
    }
}
